﻿using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Read.Api.Application.Commands.DispatchProductCommand;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Read.Api.Application.CommandsHander.DispatchProductCommandHandler
{
    public class GetDispatchCommandHandler : IRequestHandler<GetDispatchCommand, APIResult<APIPaging<DispatchProduct>>>
    {
        private readonly ISqlSugarClient db;

        public GetDispatchCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<DispatchProduct>>> Handle(GetDispatchCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<DispatchProduct>> result = new APIResult<APIPaging<DispatchProduct>>();
            result.Code = APIEnum.success;
            result.Msg = "查询显示成功";
            var list = db.Queryable<DispatchProduct>();

            if (!string.IsNullOrEmpty(request.AssociatedProjects))
            {
                list = list.Where(p => p.AssociatedProjects == request.AssociatedProjects);
            }
            if (!string.IsNullOrEmpty(request.DocumentSubject))
            {
                list = list.Where(p => p.DocumentSubject == request.DocumentSubject);
            }
            if (!string.IsNullOrEmpty(request.DocumentNumber))
            {
                list = list.Where(p => p.DocumentNumber == request.DocumentNumber);
            }
            if (!string.IsNullOrEmpty(request.SourceDocumentType))
            {
                list = list.Where(p => p.SourceDocumentType == request.SourceDocumentType);
            }
            if (!string.IsNullOrEmpty(request.SourceDocument))
            {
                list = list.Where(p => p.SourceDocument == request.SourceDocument);
            }
            if (!string.IsNullOrEmpty(request.DocumentMakers))
            {
                list = list.Where(p => p.DocumentMakers.Contains(request.DocumentMakers));
            }
            if (request.FriDocumentDate != null)
            {
                list = list.Where(p => p.DocumentDate >= request.FriDocumentDate);
            }
            if (request.EndDocumentDate != null)
            {
                list = list.Where(p => p.DocumentDate <= request.EndDocumentDate);
            }

            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.DispatchProductId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<DispatchProduct> paging = new APIPaging<DispatchProduct>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.Data = paging;

            return await Task.FromResult(result);
        }
    }
}
